const jwt = require('jsonwebtoken');
const axios = require('axios');
const { createUser, getUserByPhone, getUserByOpenid, createUserWithOpenid, getUserByEmail, getUserById } = require('../models/User');
const bcrypt = require('bcryptjs');
require('dotenv').config();

// 邮箱注册
const emailRegister = async (req, res) => {
    console.log('[AUTH] 开始邮箱注册流程', { email: req.body.email });
    try {
        const { email, password } = req.body;

        // 验证请求参数
        if (!email || !password) {
            console.warn('[AUTH] 邮箱或密码为空', { email, password: password ? '存在' : '不存在' });
            return res.status(400).json({ success: false, message: '邮箱和密码为必填项', code: 400 });
        }

        // 验证密码格式
        if (password.length < 6 || !/^(?=.*[A-Za-z])(?=.*\d).+$/.test(password)) {
            console.warn('[AUTH] 密码格式不符合要求', { email });
            return res.status(400).json({ success: false, message: '密码至少6位且包含字母和数字', code: 400 });
        }

        // 检查邮箱是否已注册
        const existingUser = await getUserByEmail(email);
        if (existingUser) {
            console.warn('[AUTH] 邮箱已被注册', { email });
            return res.status(400).json({ success: false, message: '邮箱已被注册', code: 1001 });
        }

        // 创建新用户
        const userId = await createUser({ email, password, role: 'user' });
        console.log('[AUTH] 邮箱注册成功', { userId, email });
        res.status(201).json({ success: true, message: '注册成功', code: 200, data: null });
    } catch (error) {
        console.error('[AUTH] 邮箱注册过程异常', { error: error.message });
        res.status(500).json({ success: false, message: '服务器内部错误', code: 500 });
    }
};

// 邮箱登录
const emailLogin = async (req, res) => {
    console.log('[AUTH] 开始邮箱登录流程', { email: req.body.email });
    try {
        const { email, password } = req.body;

        // 验证请求参数
        if (!email || !password) {
            console.warn('[AUTH] 邮箱或密码为空', { email, password: password ? '存在' : '不存在' });
            return res.status(400).json({ success: false, message: '邮箱和密码为必填项', code: 400 });
        }

        // 查找用户
        const user = await getUserByEmail(email);
        if (!user) {
            console.warn('[AUTH] 用户不存在', { email });
            return res.status(401).json({ success: false, message: '账号或密码错误', code: 1002 });
        }

        // 验证密码
        const isPasswordValid = await bcrypt.compare(password, user.password);
        if (!isPasswordValid) {
            console.warn('[AUTH] 密码验证失败', { email, userId: user.id });
            return res.status(401).json({ success: false, message: '账号或密码错误', code: 1002 });
        }

        // 生成token
        const token = jwt.sign({ userId: user.id, role: user.role }, process.env.JWT_SECRET, { expiresIn: '1h' });
        console.log('[AUTH] 邮箱登录成功', { userId: user.id, email, role: user.role });

        res.json({
            success: true,
            message: '登录成功',
            code: 200,
            data: {
                token,
                userInfo: {
                    id: user.id,
                    email: user.email,
                    nickname: user.nickname || '帮您省用户'
                }
            }
        });
    } catch (error) {
        console.error('[AUTH] 邮箱登录过程异常', { error: error.message, email: req.body.email });
        res.status(500).json({ success: false, message: '服务器内部错误', code: 500 });
    }
};

// 获取当前用户信息
const getCurrentUser = async (req, res) => {
    console.log('[AUTH] 开始获取当前用户信息', { userId: req.user.userId });
    try {
        const user = await getUserById(req.user.userId);
        if (!user) {
            console.warn('[AUTH] 用户不存在', { userId: req.user.userId });
            return res.status(404).json({ success: false, message: '用户不存在', code: 404 });
        }

        console.log('[AUTH] 获取用户信息成功', { userId: user.id });
        res.json({
            success: true,
            code: 200,
            data: {
                id: user.id,
                email: user.email,
                nickname: user.nickname || '帮您省用户',
                avatarUrl: user.avatar || '',
                gasCardBalance: user.gas_card_balance || 0
            }
        });
    } catch (error) {
        console.error('[AUTH] 获取用户信息过程异常', { error: error.message, userId: req.user.userId });
        res.status(500).json({ success: false, message: '服务器内部错误', code: 500 });
    }
};

// 用户登出
const logout = async (req, res) => {
    console.log('[AUTH] 用户登出', { userId: req.user.userId });
    // JWT无状态，客户端删除token即可
    res.json({ success: true, message: '登出成功', code: 200 });
};

// 管理员登录
const adminLogin = async (req, res) => {
    console.log('[AUTH] 开始管理员登录流程', { phone: req.body.phone });
    try {
        const { phone, code } = req.body;

        // 验证请求参数
        if (!phone || !code) {
            console.warn('[AUTH] 手机号或验证码为空', { phone, code: code ? '存在' : '不存在' });
            return res.status(400).json({ success: false, message: '手机号和验证码为必填项', code: 400 });
        }

        // TODO: 验证码验证逻辑
        if (code !== '123456') { // 临时验证码，实际应从缓存获取
            console.warn('[AUTH] 验证码错误', { phone });
            return res.status(401).json({ success: false, message: '验证码错误', code: 1005 });
        }

        // 查找管理员
        const user = await getUserByPhone(phone);
        if (!user || user.role !== 'admin') {
            console.warn('[AUTH] 管理员不存在', { phone });
            return res.status(403).json({ success: false, message: '管理员权限不足', code: 1006 });
        }

        // 生成token
        const token = jwt.sign({ userId: user.id, role: user.role }, process.env.JWT_SECRET, { expiresIn: '1h' });
        console.log('[AUTH] 管理员登录成功', { userId: user.id, phone, role: user.role });

        res.json({
            success: true,
            message: '登录成功',
            code: 200,
            data: {
                token,
                userInfo: {
                    id: user.id,
                    phone: user.phone,
                    role: user.role,
                    nickname: user.nickname || '系统管理员'
                }
            }
        });
    } catch (error) {
        console.error('[AUTH] 管理员登录过程异常', { error: error.message, phone: req.body.phone });
        res.status(500).json({ success: false, message: '服务器内部错误', code: 500 });
    }
};

const register = async (req, res) => {
    console.log('[AUTH] 开始用户注册流程', { body: req.body });
    try {
        const userId = await createUser(req.body);
        console.log('[AUTH] 用户注册成功', { userId });
        res.status(201).json({ message: 'User registered successfully', userId });
    } catch (error) {
        console.error('[AUTH] 注册过程异常', { error: error.message });
        res.status(500).json({ message: 'Internal server error' });
    }
};

const login = async (req, res) => {
    console.log('[AUTH] 开始手机登录流程', { phone: req.body.phone });
    try {
        const user = await getUserByPhone(req.body.phone);
        if (!user) {
            console.warn('[AUTH] 用户不存在', { phone: req.body.phone });
            console.warn('[AUTH] 密码验证失败', { phone: req.body.phone, userId: user.id });
            return res.status(401).json({ message: 'Invalid credentials' });
        }
        const isPasswordValid = await bcrypt.compare(req.body.password, user.password);
        if (!isPasswordValid) {
            return res.status(401).json({ message: 'Invalid credentials' });
        }
        const token = jwt.sign({ userId: user.id, role: user.role }, process.env.JWT_SECRET, { expiresIn: '1h' });
        console.log('[AUTH] 手机登录成功', { userId: user.id, role: user.role });
        res.json({
    token,
    adminInfo: {
        id: user.id,
        name: user.name || 'Admin',
        role: user.role
    }
});
    } catch (error) {
        console.error('[AUTH] 登录过程异常', { error: error.message, phone: req.body.phone });
        res.status(500).json({ message: 'Internal server error' });
    }
};

const wxlogin = async (req, res) => {
    console.log('[AUTH] 开始微信登录流程', { code: req.body.code ? '存在' : '不存在' });
    try {
        const { code } = req.body;
        if (!code) {
            return res.status(400).json({ code: 400, message: '缺少code参数' });
        }

        // 调用微信API获取openid
        const wxResponse = await axios.get(`https://api.weixin.qq.com/sns/jscode2session`, {
            params: {
                appid: process.env.WX_APPID,
                secret: process.env.WX_SECRET,
                js_code: code,
                grant_type: 'authorization_code'
            }
        });

        const { openid, session_key } = wxResponse.data;
        if (!openid) {
            console.warn('[AUTH] 获取微信openid失败', { response: wxResponse.data });
        return res.status(401).json({ code: 401, message: '微信登录失败' });
        }

        // 假设已在User模型中实现getUserByOpenid和createUserWithOpenid方法
        let user = await getUserByOpenid(openid);
        if (!user) {
            // 创建新用户
            user = await createUserWithOpenid(openid);
        }

        // 生成token
        const token = jwt.sign({ userId: user.id, role: user.role }, process.env.JWT_SECRET, { expiresIn: '1h' });

        console.log('[AUTH] 微信登录成功', { userId: user.id, openid });
        res.json({
            code: 200,
            message: '登录成功',
            data: {
                token,
                userInfo: {
                    id: user.id,
                    nickname: user.nickname || '',
                    avatar: user.avatar || ''
                }
            }
        });
    } catch (error) {
        console.error('[AUTH] 微信登录过程异常', { error: error.message });
        res.status(500).json({ code: 500, message: '服务器内部错误' });
    }
};

module.exports = { emailRegister, emailLogin, wxlogin, logout, getCurrentUser, adminLogin };

// 保留旧接口用于向后兼容
module.exports.oldRegister = register;
module.exports.oldLogin = login;